package com.example.purchase.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.purchase.R;
import com.example.purchase.bean.BaseBean;
import com.example.purchase.bean.MainBean;
import com.example.purchase.view.activity.DetailsActivity;

import java.util.List;

public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.MyViewHolder> {

    private BaseBean<List<MainBean>> list;
    private Context context;

    public MainRecyclerViewAdapter(BaseBean<List<MainBean>> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View rootView =  View.inflate(context, R.layout.recyclerview_main,null);
        return new MyViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(@NonNull MainRecyclerViewAdapter.MyViewHolder holder, int position) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("TAG", "onClick: " + list.getData().get(position).getId());
                context.getSharedPreferences("userMessage",Context.MODE_PRIVATE).edit().putString("id",String.valueOf(list.getData().get(position).getId())).apply();
                context.startActivity(new Intent(context, DetailsActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }
        });
        holder.title.setText(list.getData().get(position).getTitle());
        holder.info.setText(list.getData().get(position).getInfo());
        holder.city.setText(list.getData().get(position).getCity());
        holder.price.setText(String.valueOf(list.getData().get(position).getPrice()));
    }

    @Override
    public int getItemCount() {
        return list.getData().size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public final TextView title,info,price,city;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            title = itemView.findViewById(R.id.title);
            info = itemView.findViewById(R.id.info);
            price = itemView.findViewById(R.id.price);
            city = itemView.findViewById(R.id.city);
        }
    }
}
